/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof_trab1;

/**
 *
 * @author Carlos Pinheiro
 */
public class DownloadersController extends Thread
{

    private static DownloadersController dc = new DownloadersController();
    private static final int WAIT_TIME = 1000;
    private static final int THRESHOLD = 10000;

    private DownloadersController()
    {
    }

    public static DownloadersController getInstance()
    {
        return dc;
    }

    @Override
    public void run()
    {
        BandwithAllocation bwa = BandwithAllocation.getInstance();
        DownloadersLaucher dl = DownloadersLaucher.getInstance();

        try
        {
            while (!isInterrupted())
            {
                long sizeDownloading = bwa.getSizeDownloading();
                long maxDownloading = dl.getMaxBandwidthAllocation();
                if (sizeDownloading > maxDownloading)
                {
                    dl.decreaseDownloaders();
                }
                else if ((sizeDownloading + THRESHOLD) < maxDownloading)
                {
                    dl.increaseDownloaders();
                }

                Thread.sleep(WAIT_TIME);
            }
        } 
        catch (InterruptedException ex)
        {
        }
    }
}
